angular.module('tmsApp')
.controller('IndexCtrl', ['$scope', '$location', '$http', 'tmsUtil', ($scope, $location, $http, tmsUtil)->
# scope变量
  $scope.task = {
    taskName: ''
  }

  $scope.taskList = []

  #初始化数据
  init = ->
    $http.get("#{Tms.apiAddress}/api/task")
    .then((res)->
      tasks = res.data
      $scope.taskList = tasks
    , tmsUtil.processHttpError)

  #退出
  $scope.exit = ->
    $http.post("#{Tms.apiAddress}/api/user/logout")
    .then(->
      alert('注销成功！')
      $location.path('/login')
    , tmsUtil.processHttpError)

  #修改状态
  $scope.changeTaskStatus = (task)->
    task.status = if task.checked then 'Finish' else 'InProgress'

  #删除
  $scope.deleteTask = (task, index)->
    task.deleted = true
    $http.put("#{Tms.apiAddress}/api/task", task)
    .then(->
      $scope.taskList.splice(index, 1)
    , tmsUtil.processHttpError)

  #编辑
  $scope.editTask = (task)->
#标记是否在编辑
    task.isEditing = true
    task.tempTaskName = task.taskName
    $http.put("#{Tms.apiAddress}/api/task", task)
    .then((res)->
      1
    , tmsUtil.processHttpError)

  #取消编辑
  $scope.cancelEditTask = (task)->
    task.isEditing = false

  #保存编辑
  $scope.saveTask = (task)->
    oldTaskNmae = task.taskName
    task.taskName = task.tempTaskName
    $http.put("#{Tms.apiAddress}/api/task", task)
    .then((res)->
#保存成功退出编辑状态
      task.isEditing = false
    , (res)->
      task.taskName = oldTaskNmae
      tmsUtil.processHttpError
    )

  # UI操作添加
  $scope.addTask = ->
# 先把$scope.task对象复制一份当前的值再进行操作
    task = angular.copy($scope.task)
    $http.post("#{Tms.apiAddress}/api/task", {
      taskName: task.taskName
    })
    .then((res)->
      newTask = res.data
      task._id = newTask._id
      task.deleted = newTask.deleted
      # 把新提交的model push到taskList中，同时把task.taskName的值清空，使添加框的值清空
      $scope.taskList.push(task)
      $scope.task.taskName = ''
    , tmsUtil.processHttpError)

  init()
])